from olw.i18n.models import InternationalText, InternationalChar
from django.conf import settings
from django.utils.translation import gettext as _
from django import newforms
from django.utils.html import escape


class InternationalTextFormField(FormField):
    """
    This is an oldforms FormField for the internationalText
    """
    
    def __init__(self, field_name, max_length=False, is_required=False, validator_list=None, member_name=None, cols=60, rows=15, wiki=False, model = InternationalText):
        self.field_name  = field_name
        self.is_required = is_required
        self.rows, self.cols = (rows, cols)
        self.model = model
        
        if validator_list is None:
            validator_list = []
            
        # TODO: Allow max_length to validate the submitted data
        #if max_length:
        #    self.max_length = max_length
        #    validator_list += [self.isValidLength]
            
        self.validator_list = validator_list
    
    def extract_data(self, data):
        return data.get(self.field_name+'_id', '')
        

    def render(self, data):
        if data is None:
            data = ''
        try:
            itext = self.model.objects.get(pk = data)
            lang, text = itext.render_with_lang()
        except:
            itext = self.model()
            lang  = settings.LANGUAGE_CODE
            text  = ''


        
        return """
<div class="i18n" style="border: 0; padding:0; margin:0;" id="%s__div">
<table style="border: 0; padding: 0; margin: 0; vertical-align: top;">
<tr>
  <td>
     <input type="hidden" id="%s" name="%s" value="%s" />
     <input type="hidden" id="%s__type" name="%s__type" value="%s" />
     <input type="hidden" id="%s__curlang" name="%s__curlang" value="%s" />
     <input type="hidden" id="%s__langs" name="%s__langs" value="%s," />
     <textarea class="i18n" name="%s__edited__rawtext" rows="%s" cols="%s"
        id="%s__edited__rawtext" >%s</textarea>
  </td>
  <td>
     <select class="i18n" name="%s__edited__lang">
     %s
     </select>
     <br />
     %s 
  </td>
</tr>
</table>
</div>
        """ % (self.field_name, self.field_name, self.field_name, data,
               self.field_name, self.field_name, str(self.model.__name__),
               self.field_name, self.field_name, lang,
               self.field_name,
               self.field_name, lang,
               self.field_name, self.rows, self.cols, self.field_name,
               escape(text), self.field_name, 
               self.language_field(lang),
               self.progress_field(itext))


    def progress_field(self, itext):
        langs = settings.LANGUAGES
        html = """
<style type="text/css">
.lang_progress th, .lang_progress td {
    border: 1px solid black;
}
</style>
<table class="lang_progress" style="border: 1px solid black; ">
<tr>
  <th colspan="%s">Languages</th>
</tr>
<tr>
""" % len(langs)
        header, body = ([],[])
        yes_img = '<img src="%simg/admin/icon-yes.gif" border="0" title="%%s" />' % \
                  settings.ADMIN_MEDIA_PREFIX

        no_img = '<img src="%simg/admin/icon-no.gif" border="0" />' % \
                  settings.ADMIN_MEDIA_PREFIX
        
        for lang in langs:
            header.append('<th title="%s">%s</th>' % (_(lang[1]), lang[0]))
            
            modified = itext.get_lang_time(lang[0])
            if modified:
                body.append('<td>%s</td>' % (yes_img % ('%s/%s/%s' % (modified.month,
                                                                      modified.day,
                                                                      modified.year))))
            else:
                body.append('<td>%s</td>' % no_img)

        return html + '\n'.join(header) + '\n</tr><tr>\n' + '\n'.join(body) + '</tr></table>'
        

    def language_field(self, lang):
        languages = []
        langs = settings.LANGUAGES
        match_subset = False

        if lang not in [x[0] for x in langs]:
            match_subset = True

        matched = False
        for code, text in langs:
            match = False

            if match_subset and not matched and \
                lang[:2].lower() == code[:2].lower():
                match = True
            if lang.lower() == code.lower():
                match = True

            languages.append('<option value="%s"%s>%s</option>' % \
                             (code, match and ' selected="selected"' or '',
                             _(text)))
        return '\n'.join(languages)

    def prepare(self, new_data):
        id = new_data.get(self.field_name, None)
            
        texts = {}
        languages = new_data.get(self.field_name+'__langs', '').strip(',').split(',')
        
        if id == None or id == '':
            itext = self.model()
            itext.save()
        else:
            try:
                itext = self.model.objects.get(pk = id)
            except:
                itext = self.model(id = id)
                itext.save()

        
        
        for lang in languages:
            lang_key = '%s__edited__lang' % (self.field_name)
            text_key = '%s__edited__rawtext' % (self.field_name)
            
            if new_data.has_key(lang_key) and new_data.has_key(text_key):
                itext.set_lang(new_data[lang_key], new_data[text_key])

        new_data[self.field_name] = itext.id
       


